import { useEffect, useRef } from 'react'
import { useSetState } from 'ahooks'
import draggable from '../draggable'

const Slider = ({ color, onChange }) => {
  const $el = useRef(null)
  const bar = useRef(null)
  const thumb = useRef(null)

  const [state, setState] = useSetState({
    thumbLeft: 0,
    background: null
  })

  useEffect(() => {
    const dragConfig = {
      drag: (event) => {
        handleDrag(event)
      },
      end: (event) => {
        handleDrag(event)
      }
    }
    draggable(bar.current, dragConfig)
    draggable(thumb.current, dragConfig)
    update()
  }, [])

  const handleClick = (event) => {
    const target = event.target
    if (target !== thumb.current) {
      handleDrag(event)
    }
  }

  const handleDrag = (event) => {
    const rect = $el.current.getBoundingClientRect()
    let left = event.clientX - rect.left
    left = Math.max(thumb.current.offsetWidth / 2, left)
    left = Math.min(left, rect.width - thumb.current.offsetWidth / 2)
    color.set(
      'alpha',
      Math.round(
        ((left - thumb.current.offsetWidth / 2) / (rect.width - thumb.current.offsetWidth)) * 100
      )
    )
    update()
    onChange(color)
  }

  const getThumbLeft = () => {
    const el = $el.current
    const alpha = color._alpha
    if (!el) return 0
    return Math.round((alpha * (el.offsetWidth - thumb.current.offsetWidth / 2)) / 100)
  }

  const getBackground = () => {
    if (color && color.value) {
      const { r, g, b } = color.toRgb()
      return `linear-gradient(to right, rgba(${r}, ${g}, ${b}, 0) 0%, rgba(${r}, ${g}, ${b}, 1) 100%)`
    }
    return null
  }

  const update = () => {
    setState({
      thumbLeft: getThumbLeft(),
      background: getBackground()
    })
  }

  const { thumbLeft, background } = state
  return (
    <div ref={$el} className="color-alpha-slider">
      <div
        className="color-alpha-slider__bar"
        onClick={handleClick}
        ref={bar}
        style={{ background }}
      />
      <div className="color-alpha-slider__thumb" ref={thumb} style={{ left: thumbLeft + 'px' }} />
    </div>
  )
}

export default Slider
